package rsj.service;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.TableNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import rsj.entity.Menu;
import rsj.sql.auth.RoleMenuDao;
import rsj.utils.RedisUtils;

import java.util.List;

/**
 * 缓存菜单
 *
 * @author yuanqinglong
 * @since 2021/5/28 11:57
 */
@Component
@EnableAsync
public class CacheMenuService {

    protected static Logger logger = LoggerFactory.getLogger(CacheMenuService.class);

    @Autowired
    private RoleMenuDao roleMenuDao;

    private static final String MENU_KEY = "rsj:login_menu_auth:%s";
    /**
     * 过期时间
     */
    private static final long EXPIRE = 60L * 30;

    /**
     * 保存菜单缓存,
     *
     * @param menuList 菜单列表
     * @param userId   用户id
     */
    @Async
    public void asyncSaveMenuToRedis(TableNode menuList, String userId) {
        String resourceKey = String.format(MENU_KEY, userId);
        RedisUtils.set(resourceKey, menuList.toJson(), EXPIRE);
        logger.info("保存菜单缓存成功、key:{}", resourceKey);
    }


    /**
     * 用户id获取菜单
     *
     * @param userId 用户id
     */
    public List<Menu> getMenuByUserId(String userId) {
        String resourceKey = String.format(MENU_KEY, userId);
        Object menus = RedisUtils.get(resourceKey);
        if (menus == null) {
            TableNode tableNode = roleMenuDao.queryMenuByUserId(userId);
            this.asyncSaveMenuToRedis(tableNode, userId);
            return JSON.parseArray(tableNode.toJson(), Menu.class);
        }
        return JSON.parseArray(menus.toString(), Menu.class);
    }
}
